<template>
  <div>
    <div style="width: 100%;">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="150px" :size="formSize" status-icon
        :inline="true">

        <el-form-item label="单据编号" prop="salesForecastCode" style="width: 20%;min-width: 150px;">
          <el-input class="elFormItem100PX" v-model="ruleForm.salesForecastCode" disabled />
        </el-form-item>
        <br>
        <el-form-item label="项目名称" prop="projectName" style="width: 20%;min-width: 150px;">
          <el-input class="elFormItem100PX" v-model="ruleForm.projectName" />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="ruleForm.projectType" class="elFormItem100PX" placeholder="项目类型">
            <el-option label="WMS" value="WMS" />
            <el-option label="MES" value="MES" />
            <el-option label="AGV" value="AGV" />
            <el-option label="SCADA" value="SCADA" />
            <el-option label="SAP" value="SAP" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="state">
          <el-select v-model="ruleForm.state" class="elFormItem100PX" placeholder="项目类型">
            <el-option label="跟踪中" :value=1 />
            <el-option label="丢单" :value=2 />
            <el-option label="客户取消" :value=3 />
            <el-option label="已签订" :value=4 />
          </el-select>
        </el-form-item>

        <br>

        <el-form-item label="客户名称" prop="custName">
          <el-select v-model="ruleForm.custName" filterable @click="on_getCustName" :filter-method="getCustName"
            class="elFormItem100PX">
            <el-option v-for="item in optionsCustName" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户联系方式" prop="custPhone">
          <el-input class="elFormItem100PX" v-model="ruleForm.custPhone" />
        </el-form-item>

        <el-form-item label="客户地址" prop="custAddress">
          <el-input class="elFormItem100PX" v-model="ruleForm.custAddress" autosize type="textarea"
            placeholder="Please input" />
        </el-form-item>

        <br>

        <el-form-item label="预计金额（万元）" prop="estAmount">
          <el-input class="elFormItem100PX" v-model="ruleForm.estAmount" type="number" />
        </el-form-item>

        <el-form-item label="是否需要方案" prop="isScheme">
          <el-switch v-model="ruleForm.isScheme" size="small" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>

        <br>


        <el-form-item label="预计启动时间" prop="estimatedStartTime">
          <el-date-picker v-model="ruleForm.estimatedStartTime" type="date" placeholder="Pick a date"
            value-format="YYYY-MM-DDT00:00:00" />
        </el-form-item>
        <el-form-item label="预计结束时间" prop="estimatedEndTime">
          <el-date-picker v-model="ruleForm.estimatedEndTime" type="date" placeholder="Pick a date"
            value-format="YYYY-MM-DDT00:00:00" />
        </el-form-item>
        <el-form-item label="要求方案提交日期" prop="schemeTime">
          <el-date-picker v-model="ruleForm.schemeTime" type="date" placeholder="Pick a date"
            value-format="YYYY-MM-DDT00:00:00" />
        </el-form-item>
        <el-form-item label="方案实际提交时间" prop="schemeActualTimes">
          <el-date-picker v-model="ruleForm.schemeActualTimes" type="date" placeholder="Pick a date"
            value-format="YYYY-MM-DDT00:00:00" />
        </el-form-item>


        <br>

        <el-form-item label="跟踪状态" prop="trackingState">
          <el-input class="elFormItem100PX" v-model="ruleForm.trackingState" autosize type="textarea"
            placeholder="Please input" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input class="elFormItem100PX" v-model="ruleForm.remark" autosize type="textarea"
            placeholder="Please input" />
        </el-form-item>
        <div v-if="salesType == 'upd'">
          <el-text style="margin-left: 100px;" class="mx-1" type="primary">制单人：{{ ruleForm.userName }}</el-text>
          <el-text style="margin-left: 100px;" class="mx-1" type="success">修改人：{{ ruleForm.updUserName }}</el-text>
          <el-text style="margin-left: 20px;" class="mx-1" type="success">
            <el-date-picker size="small" disabled v-model="ruleForm.updateTime" type="datetime"
              placeholder="Select date and time" />
          </el-text>

        </div>


        <br>
        <br>
        <div style="margin-left: 20%;">
          <el-form-item v-if="salesType == 'add'">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">清除</el-button>
          </el-form-item>

          <el-form-item v-else-if="salesType == 'upd'">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </div>

      </el-form>
    </div>
    <div v-if="salesType == 'upd'" :key="salesHistoryState">
      <history :param="route.params.salesForecastCode" />
    </div>
  </div>
</template>
<style scoped >
.elFormItem100PX {
  min-width: 200px;
}

.custom-row {
  margin-bottom: 20px;
  /* 或者使用 padding-bottom */
}
</style>
<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import api from '/@/api/sy/apiERP.js';
import { v } from 'vxe-table';
import { useRoute, useRouter } from "vue-router";

// 历史纪录，单独子页面
import history from '/@/views/erp/sales/salesforecast_upd_history.vue';



// 路由跳转到其他指定页面
const router = useRouter();

// 接收动态路由跳转传参
const route = useRoute();

//全局判断，新增还是修改
var salesType = ref('add')

//历史记录刷新
var salesHistoryState = ref(0)

// 新增与修改
interface RuleForm {
  salesID: number | null
  salesForecastCode: string | null
  projectType: string | null
  projectName: string | null
  custName: string | null
  custPhone: string | null
  custAddress: string | null
  isScheme: boolean | null
  estAmount: number | null
  estimatedStartTime: Date | null
  estimatedEndTime: Date | null,
  schemeTime: Date | null
  schemeActualTimes: Date | null
  trackingState: string | null
  state: number | null
  remark: string | null
  userName: string | null
  updUserName: string | null
  updateTime: Date | null
  createTime: Date | null
  oriUpdateTime: Date | null
}

interface Option {
  value: string
  label: string
}
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
let ruleForm = ref<RuleForm>({
  salesID: 0,
  salesForecastCode: '',
  projectType: null,
  projectName: null,
  custName: null,
  custPhone: null,
  custAddress: null,
  isScheme: false,
  estAmount: null,
  estimatedStartTime: null,
  estimatedEndTime: null,
  schemeTime: null,
  schemeActualTimes: null,
  trackingState: '',
  state: null,
  remark: '',
  userName: null,
  updUserName:null,
  updateTime: null,
  createTime: null,
  oriUpdateTime: null,
})
var optionsCustName = ref<Option[]>()
const rules = reactive({
  salesForecastCode: [
    { required: true, message: '编号不可为空', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  projectType: [
    {
      // type: 'array',
      required: true,
      message: '请至少选一个类型',
      trigger: 'change',
    },
  ],
  state: [
    {
      // type: 'number',
      required: true,
      message: '请至少选一个类型',
      trigger: 'change',
    },
  ],
  projectName: [
    {
      required: true,
      message: '项目名称不可为空',
      trigger: 'change',
    },
  ],
  custName: [
    {
      required: true,
      message: '客户名称',
      trigger: 'change',
    },
  ],
  custPhone: [
    {
      required: true,
      message: '客户联系方式',
      trigger: 'change',
    },
  ],
  // estimatedStartTime: [
  //   {
  //     type: 'date',
  //     required: true,
  //     message: '请填写正确的时间',
  //     trigger: 'change',
  //   },
  // ],
  estAmount: [
    {
      required: true,
      message: '金额需要填写',
      trigger: 'blur'
    },
  ],
})


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (salesType.value == 'add') {
        addSales(formEl)
      } else if (salesType.value == 'upd') {
        updSales(formEl)
      }
    } else {
    }
  })
}


function on_getCustName() {
  getCustName('')
}
function getCustName(query: any) {
  api.post('public/sales/salesForecastADD_getCustName', query, {
    headers: {
      'Content-Type': 'text/plain', // 设置请求体的类型为纯文本
    },
  }).then((response: any) => {
    optionsCustName.value = []
    for (const a of response.data.data) {
      optionsCustName.value?.push({ label: a, value: a })
    }

    var ab = optionsCustName.value.some(option => option.label === query)
    if (!ab && query.length > 0) {
      optionsCustName.value?.push({ label: (query + '(该客户不存在，可强制选择)'), value: query })
    }

    // 处理服务器返回的响应
  })
    .catch((error: any) => {


      // 处理错误
    })
    .finally(() => {

    })

}



const resetForm = (formEl: FormInstance | undefined) => {

  if (!formEl) return
  if (salesType.value == 'upd') {
    upd_getSales(route.params.salesForecastCode as string)
  } else if (salesType.value == 'add') {
    formEl.resetFields()
    salesADD_getsalesForecastCode()
  }
}

//获取传参的项目编号。所存在的数据。用于修改
function upd_getSales(val: string) {
  // console.log(1)
  api.post('public/sales/getSalesForecast_User', { 'salesForecastCode': val }).then((response: any) => {
    // 处理服务器返回的响应

    if (response.data.data == null) {
      alert('查询的编号不存在')
      router.replace('/sy/sales_upd');
    } else {
      ruleForm.value = response.data.data
    }

  }).catch((error: any) => { }).finally(() => { })
}




//获取传参的项目编号。所存在的数据。用于修改
function upd_sales(val: string) {
  api.post('public/sales/getSalesForecast_User', { 'salesForecastCode': val }).then((response: any) => {
    // 处理服务器返回的响应
    ruleForm.value = response.data.data

  })
    .catch((error: any) => {

      // 处理错误
    })
    .finally(() => {

    })
}

function addSales(formEl: FormInstance | undefined) {
  var param = ruleForm.value
  api.post('public/sales/salesForecastADD', param).then((response: any) => {
    // 处理服务器返回的响应
    if (response.data.code == 200) {
      alert('新增成功')
      resetForm(formEl)
    }
  }).catch((error: any) => { }).finally(() => { })
    ;
}
function updSales(formEl: FormInstance | undefined) {
  var param = ruleForm.value
  api.post('public/sales/salesForecastUPD', param).then((response: any) => {
    // 处理服务器返回的响应
    if (response.data.code == 200) {
      alert('保存成功')
      resetForm(formEl)
    }
  }).catch((error: any) => { }).finally(() => {

    salesHistoryState.value = salesHistoryState.value+1
    console.log(salesHistoryState.value);
    
  })
    ;
}
function salesADD_getsalesForecastCode() {

  api.post('public/sales/salesForecastADD_getsalesForecastCode').then((response: any) => {
    // 处理服务器返回的响应
    ruleForm.value.salesForecastCode = response.data.data
  })
    .catch((error: any) => {

      // 处理错误
    })
    .finally(() => {
    })

    ;
}
onMounted(() => {
  // name 值为路由中的 name
  if (route.params.salesForecastCode.length > 0) {
    salesType.value = 'upd'
    upd_getSales(route.params.salesForecastCode as string)
  } else {
    salesType.value = 'add'
    salesADD_getsalesForecastCode()
  }


  // 在这里写逻辑
});
</script>
